<!--
 * @Descripttion: 备件台账表单
 * @LastEditors: xzh
 * @LastEditTime: 2023-10-13 22:23:52
-->
<template>
  <DileDrawer
    v-model="spareLedgerFrom.visible"
    :loading="spareLedgerFrom.loading"
    size="80%"
    @sure="hanldeSure"
  >
    <template #header>
      <span>{{
        $t(`table.btnArr.${!spareLedgerFrom.formData.id ? "add" : "edit"}`)
      }}</span>
    </template>
    <template #default>
      <el-form
        ref="formRef"
        class="el-form-card"
        :model="spareLedgerFrom.formData"
        :rules="formRules"
        label-width="6rem"
        size="large"
        status-icon
      >
        <!-- 备件信息 -->
        <el-card>
          <template #header>
            <span>{{
              $t("page.equipSpareArr.spareLedgerArr.spareLedgerInfo")
            }}</span>
          </template>

          <el-col :span="12">
            <el-form-item :label="$t('page.equipSpareArr.spareLedgerArr.code')">
              <el-input
                v-model="spareLedgerFrom.formData.code"
                disabled
                :placeholder="$t('common.systemAutoGenerate')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipSpareArr.spareLedgerArr.name')"
              prop="name"
            >
              <el-input
                v-model="spareLedgerFrom.formData.name"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipSpareArr.spareLedgerArr.specification')"
            >
              <el-input
                v-model="spareLedgerFrom.formData.specification"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.equipSpareArr.spareType')">
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="spareLedgerFrom.formData.typeId"
                :selectType="selectTypeEnum.equipSpareType"
                :cacheLabel="spareLedgerFrom.formData.extJson.typeName"
                :expand-on-click-node="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.equipSpareArr.spareLedgerArr.unit')">
              <el-select
                v-model="spareLedgerFrom.formData.unit"
                :placeholder="$t('common.select')"
              >
                <el-option
                  v-for="item in spareLedgerFrom.resoure.calcUnitArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipSpareArr.spareLedgerArr.manufacturer')"
            >
              <el-input
                v-model="spareLedgerFrom.formData.manufacturer"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('common.remark')">
              <el-input
                v-model="spareLedgerFrom.formData.remark"
                :rows="5"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-card>
        <!-- 库存信息 -->
        <el-card>
          <template #header>
            <span>{{
              $t("page.equipSpareArr.spareLedgerArr.inventoryInfo")
            }}</span>
          </template>
          <el-col :span="12">
            <el-form-item
              :label="
                $t('page.equipSpareArr.spareLedgerArr.inventoryUpperLimit')
              "
              prop="inventoryUpperLimit"
            >
              <el-input-number
                v-model="spareLedgerFrom.formData.inventoryUpperLimit"
                controls-position="right"
                :min="0"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="
                $t('page.equipSpareArr.spareLedgerArr.inventoryLowerLimit')
              "
            >
              <el-input-number
                v-model="spareLedgerFrom.formData.inventoryLowerLimit"
                controls-position="right"
                :min="0"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipSpareArr.spareLedgerArr.replacementCycle')"
              class="form-item-flex"
            >
              <el-input-number
                v-model="spareLedgerFrom.formData.replacementCycle"
                controls-position="right"
                :min="1"
                :placeholder="$t('common.enter')"
              />
              <el-select
                v-model="spareLedgerFrom.formData.replacementCycleUnit"
              >
                <el-option
                  v-for="timeType in Object.keys(timeTypeEnum)"
                  :key="timeType"
                  :label="$t(`common.timeTypeArr.${timeType}`)"
                  :value="timeType"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="
                $t('page.equipSpareArr.spareLedgerArr.InventoryTotalLimit')
              "
            >
              <el-input
                v-model="spareLedgerFrom.formData.inventoryTotalLimit"
                readonly
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
        </el-card>
        <!-- 关联设备 -->
        <el-card>
          <template #header>
            <span>{{ $t("page.equipSpareArr.spareLedgerArr.relEquip") }}</span>
          </template>
          <!-- 关联设备 -->
          <RelEquipList ref="relEquipRef">
            <template #extClounm>
              <vxe-column
                field="equipmentPart"
                :title="$t('page.equipManageArr.equipmentPart')"
              >
                <template #default="{ row }">
                  <el-input v-model="row.equipmentPart" size="default" />
                </template>
              </vxe-column>
            </template>
          </RelEquipList>
        </el-card>
      </el-form>
    </template>
  </DileDrawer>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, nextTick, toRef } from "vue";
import { type object_Inf, timeTypeEnum } from "@/utils/typings/index.type";
import { useI18n } from "vue-i18n";
import { ElNotification } from "element-plus";
import { selectTypeEnum } from "@/components/dile-selectItem/index.type";
import RelEquipList from "@/views/equipManage/equipBaseInfo/equipArchives/equipArchives-relTable/index.vue";
import DileInputSelectItem from "@/components/dile-selectItem/selectItem-input/index.vue";
import DileDrawer from "@/components/dile-drawer/index.vue";
import Dile_APi from "@/api";
import Dile_Methods from "@/utils/methods";

const emit = defineEmits(["refresh"]);

let { t } = useI18n();

/**
 * @Author: xzh
 * @Descripttion: 表单默认数据
 * @Param:
 */
let defaultData = () => ({
  id: 0,
  status: true, //状态
  //备件信息
  name: "", //备件台账名称
  code: "", //备件台账编码
  specification: "", //规格型号
  typeId: null, //备件类型
  unit: "", //单位
  manufacturer: "", //生产厂商
  remark: "", //备注
  //库存信息
  inventoryUpperLimit: 0, //库存上限
  inventoryLowerLimit: 0, //库存下限
  inventoryTotalLimit: 0, //总库存
  replacementCycle: 1, //更换周期
  replacementCycleUnit: timeTypeEnum.day, //周期类型
  extJson: {
    typeName: "", //备件类型名称
  },
});
/**
 * @Author: xzh
 * @Descripttion: 备件台账表单参数
 * @Param:
 */
let spareLedgerFrom = reactive<object_Inf>({
  visible: false,
  loading: false,
  //表单数据
  formData: defaultData(),
  resoure: {
    //计量单位
    calcUnitArr: [],
  },
});

/**
 * @Author: xzh
 * @Descripttion: 表单实例
 * @Param:
 */
let formRef = ref<any>(null);
/**
 * @Author: xzh
 * @Descripttion: 关联设备
 * @Param:
 */
let relEquipRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion:表单验证规则
 * @Param:
 * @param {*} computed
 */
let formRules = computed((): any => {
  return reactive({
    name: [
      {
        required: true,
        message:
          t("common.enter") + t("page.equipSpareArr.spareLedgerArr.name"),
        trigger: "change",
      },
    ],
    inventoryUpperLimit: [
      {
        required: true,
        message:
          t("common.enter") +
          t("page.equipSpareArr.spareLedgerArr.inventoryUpperLimit"),
        trigger: "change",
      },
    ],
  });
});

/**
 * @Author: xzh
 * @Descripttion:初始化加载
 * @Param:
 * @param {*} id 备件台账主键
 */
let init = async (id: number) => {
  let { visible, loading } = toRefs(spareLedgerFrom);
  visible.value = true;
  await nextTick();
  try {
    loading.value = true;
    //加载表单资源
    await initSearchResource();
    //加载表单数据
    await initFormData(id);
  } finally {
    loading.value = false;
  }
};
/**
 * @Author: xzh
 * @Descripttion: 加载表单资源
 * @Param:
 */
let initSearchResource = async () => {
  //加载计量单位资源
  await initCalcUnitArrResource();
};

/**
 * @Author: xzh
 * @Descripttion: 加载计量单位资源
 * @Param:
 */
let initCalcUnitArrResource = async () => {
  let calcUnitArr = toRef(spareLedgerFrom.resoure, "calcUnitArr");
  //加载所有设备状态
  calcUnitArr.value = Dile_Methods.filterDataArr(
    (await Dile_APi.getCalcUnitList())?.map((calcUnit: object_Inf) => ({
      value: calcUnit.id,
      label: calcUnit.name,
    }))
  );
};

/**
 * @Author: xzh
 * @Descripttion: 加载表单数据
 * @Param:
 */
let initFormData = async (id: number) => {
  let { model, dataList, relations }: object_Inf = !!id
    ? await Dile_APi.getEquipSpareLedgerInfo(id)
    : { model: defaultData() };
  Object.assign(spareLedgerFrom.formData, model);
  //格式化关联设备信息
  if (dataList?.length > 0) {
    let relEquipArr = dataList
      .map((equip: object_Inf) => {
        let { id, equipmentPart } = relations?.find(
          (x: object_Inf) => x.equipmentId == equip.id
        );
        return !!id
          ? {
              ...equip,
              equipmentPart,
              relId: id,
            }
          : {};
      })
      .filter((x: object_Inf) => !!x.id);
    //加载关联设备表格
    relEquipRef.value.initTableData(relEquipArr);
  }
};

/**
 * @Author: xzh
 * @Descripttion: 保存事件
 * @Param:
 */
let hanldeSure = async () => {
  let { formData, loading, visible } = toRefs(spareLedgerFrom),
    valid = await formRef.value.validate();
  if (!valid || !!loading.value) {
    return false;
  }
  try {
    loading.value = true;
    let { id } = formData.value,
      relData: object_Inf = relEquipRef.value.getRelData();
    //格式化关联设备信息
    Object.keys(relData)
      .filter((x) => x != "deleteRelations")
      .forEach(
        (relkey) =>
          (relData[relkey] = relData[relkey].map((x: object_Inf) => {
            let { id: equipmentId, equipmentPart, relId } = x;
            return {
              id: relId,
              sparePartId: id,
              equipmentId,
              equipmentPart,
            };
          }))
      );

    await Dile_APi.saveEquipSpareLedger({
      model: formData.value,
      ...relData,
    });
    //触发刷新回调
    emit("refresh");
    //提示成功
    ElNotification({
      message: t("common.message.OperationSuccess"),
      type: "success",
    });
    //关闭弹框
    visible.value = false;
  } finally {
    loading.value = false;
  }
};

defineExpose({
  init,
});
</script>
<style lang="scss" scoped>
.el-form {
  :deep(.el-card__body) {
    .form-item-flex {
      .el-form-item__content {
        display: flex;
        justify-content: space-between;
        gap: 0.5rem;
        .el-select {
          flex: 5rem 0 0;
        }
        .el-input-number {
          flex: 1;
        }
      }
    }
  }
}
</style>
